package cn.caijiapeng.spt.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

import cn.caijiapeng.spt.bean.Operate;
import cn.caijiapeng.spt.bean.Resp;
import cn.caijiapeng.spt.bean.Resp.Code;
import cn.caijiapeng.spt.config.WebConst;
import cn.caijiapeng.spt.model.SysAccess;
import cn.caijiapeng.spt.service.SysAccessService;

public class AdminInterceptor implements Interceptor{

	public void intercept(Invocation inv) {
		Controller c = inv.getController();
		String token = c.getHeader("SPT-Token");
		if(StrKit.isBlank(token)) {
			c.renderJson(Resp.by(Code.ACCESS_TOKEN_INVALID, "无效的TOKEN"));
			return;
		}
		Operate<SysAccess> access = SysAccessService.srv.findByToken(token);
		if(access.notOk()) {
			c.renderJson(Resp.by(Code.ACCESS_TOKEN_INVALID, "无效的TOKEN"));
			return;
		}
		if(System.currentTimeMillis() - access.get().getLong("refresh_time") > access.get().getInt("expires_in") * 1000) {
			c.renderJson(Resp.by(Code.ACCESS_TOKEN_INVALID, "登录已失效，请重新登录"));
			return;
		}
		SysAccessService.srv.refreshToken(access.get().getInt("id"));
		c.setAttr(WebConst.LOGIN_SYS_ACCESS, access.get());
		inv.invoke();
		
	}

	
	
}
